package com.zyj.exam_app.exam.service.impl;

import com.zyj.exam_app.exam.bean.ExamPaper;
import com.zyj.exam_app.exam.bean.UserAnswer;
import com.zyj.exam_app.exam.mapper.ExamPaperMapper;
import com.zyj.exam_app.exam.mapper.UserAnswerMapper;
import com.zyj.exam_app.exam.service.ExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Component
public class ExamServiceImpl implements ExamService {
    @Autowired
    private ExamPaperMapper examPaperMapper;
    @Autowired
    private UserAnswerMapper userAnswerMapper;

    @Override
    public List<ExamPaper> getExamPaperOfUser(String userId) {
        //校验参数

        //查询列表
        return examPaperMapper.selectExamPaperByUserId(userId);
    }

    @Override
    @Transactional(readOnly = false, isolation = Isolation.DEFAULT,
            rollbackForClassName = {"com.zyj.exam_app.exception.ServiceException"}, propagation = Propagation.REQUIRED)
    public void submitExam(ExamPaper examPaper) {
        //参数校验

        //保存答卷
        examPaperMapper.insertOneExamPaper(examPaper);
        System.out.println(examPaper.getId());
        //保存答案
        List<UserAnswer> userAnswerList = examPaper.getAnswerList();
        int nums = userAnswerMapper.batchInsert(userAnswerList, examPaper.getId());
        //评分
        List<UserAnswer> rightUserAnswers = userAnswerMapper.selectRightUserAnswer(examPaper.getId());
        double mark = rightUserAnswers.size() / ((double)nums);
        examPaper.setAchievement(calcAchievement(mark));
        //更新成绩
        examPaperMapper.updateExamPaperById(examPaper);
        System.out.println("插入行数：" + nums);
    }

    /**
     * 计算成绩，按照正确率划分等级
     * @param mark
     * @return
     */
    private String calcAchievement(double mark){
        if(mark > 0.9){
            return "优秀";
        }
        if(mark > 0.8){
            return "良好";
        }
        if(mark > 0.6){
            return "及格";
        }
        return "不及格";
    }
}
